#include "cubeMesh.h"

using namespace sde;

CubeMesh::CubeMesh(std::string _type, std::string _name, Object* _object) :
    SceneNode(_type,_name,_object),
    entity(0),
    localSceneNode(0) {
}

void CubeMesh::run() {
    SceneNode::run();
    
    if (sceneManager && sceneNode) {
        entity = sceneManager->createEntity(object->name,Ogre::SceneManager::PT_CUBE);
        localSceneNode = sceneNode->createChildSceneNode(object->name + std::string("_child"));
        localSceneNode->attachObject(entity);
        
        Ogre::Vector3 size = entity->getBoundingBox().getMaximum() - entity->getBoundingBox().getMinimum();
        localSceneNode->setScale(1.0 / size.x, 1.0 / size.y, 1.0 / size.z);
        
        updateMaterial(object->getVar("material",std::string("Examples/RustySteel")));
        object->subscribeSetVar("material",boost::bind(&CubeMesh::updateMaterial,this,_1));
    }
}

void CubeMesh::updateMaterial(Var val) {
    if (entity && boost::any_cast<std::string>(&val)) {
        std::string material = boost::any_cast<std::string>(val);
        entity->setMaterialName(material);
    }
}

void CubeMesh::stop() {
    if (localSceneNode) {
        localSceneNode->getParentSceneNode()->removeChild(localSceneNode);
    }

    SceneNode::stop();
}
